﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;

namespace Servicios.Cuestionarios.Controllers
{
    public class StreammingController : ApiController
    {

        public HttpResponseMessage Get(string filename, string ext)
        {
            //var video = new MultimediaStreammingHelper(filename, ext);

            var mediaType = "image/jpg";

            switch (ext.ToUpper())
            {
                case "MP3":
                    mediaType = "audio/mp3";
                    break;
                case "MP4":
                    mediaType = "video/mp4";
                    break;
                default:
                    break;
            }

            var response = Request.CreateResponse();
            response.Content = new PushStreamContent(async (Stream outputStream, HttpContent content, TransportContext context) =>
            {
                try
                {
                    var buffer = new byte[65536];

                    using (var video = File.Open(ConfigurationManager.AppSettings["DirPath"] + filename , FileMode.Open, FileAccess.Read))
                    {
                        var length = (int)video.Length;
                        var bytesRead = 1;

                        while (length > 0 && bytesRead > 0)
                        {
                            bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                            await outputStream.WriteAsync(buffer, 0, bytesRead);
                            length -= bytesRead;
                        }
                    }
                }
                finally
                {
                    outputStream.Close();
                }
            }, new MediaTypeHeaderValue(mediaType));

            return response;
        }

    }
}
